package com.chookss.home.gallery;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.aliyun.svideo.common.utils.NetUtils;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.ContactEntity;
import com.chookss.home.entity.UploadEntity;
import com.chookss.home.logContacts.ContactsLogChoiceActivity;
import com.chookss.mine.personal.upload.UploadFileService;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.GridSpacingItemDecoration;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PathUtil;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.Utils;
import com.chookss.video.VideoNewCatesActivity;
import com.chookss.view.BottomListsDialog;
import com.chookss.view.GlideEngine;
import com.chookss.view.ImageFileCompressEngine;
import com.chookss.view.MyRoundLayout;
import com.chookss.view.SelectDialogListener;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.luck.picture.lib.animators.AnimationType;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lvgroup.hospital.base.BaseAct;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.interfaces.OnInputConfirmListener;
import com.lxj.xpopup.interfaces.SimpleCallback;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PublishGalleryActivity extends BaseAct {
    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.edKey)
    EditText edKey;
    @BindView(R.id.tvChoiceLabel)
    TextView tvChoiceLabel;
    @BindView(R.id.tvDirectory)
    TextView tvDirectory;
    @BindView(R.id.tvChoieDirectory)
    TextView tvChoieDirectory;
    @BindView(R.id.tvLocation)
    TextView tvLocation;
    @BindView(R.id.tvChoieLocation)
    TextView tvChoieLocation;
    @BindView(R.id.tvProvider)
    TextView tvProvider;
    @BindView(R.id.tvType)
    TextView tvType;
    @BindView(R.id.tvOriginal)
    TextView tvOriginal;
    @BindView(R.id.ivBg)
    View ivBg;
    @BindView(R.id.ivChoice)
    ImageView ivChoice;
    @BindView(R.id.ivChoice2)
    ImageView ivChoice2;
    @BindView(R.id.rlChoice)
    RelativeLayout rlChoice;
    @BindView(R.id.tv_publish)
    TextView tvPublish;
    private BottomListsDialog typeDialog;
    private BottomListsDialog originalDialog;
    private String imgOpenStatus = "0";//0公开1私密
    private String imgOriginal = "1";//(0-否 1-是)',
    private ArrayList<String> imgList = new ArrayList<>();
    private MyImagsAdapter adapter;
    private int shareFlag = 1; //1分享 0不允许分享
    private String tagCode, directoryName, directoryCode;//标签code 目录code
    private String provideEmployeeCode, provideEmployeeName;//提供人code 和name  默认是发布者
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private String province = "", city = "", district = "", latitude = "", longitude = "";
    private static int SOURSE = 7;//选员工所用标识
    private UploadEntity uploadEntity;
    private boolean uploadStatus = true;//false表示上传失败进来的需要重新上传
    private String uploadTag = "";//上传失败进来的需要重新上传

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_gallery);
        ButterKnife.bind(this);
        initState();
    }

    @Override
    public void initData() {
        commonTitleTxt.setText("发布");
        uploadTag = getIntent().getStringExtra("uploadTag");
        uploadStatus = getIntent().getBooleanExtra("uploadStatus", true);
        if (uploadStatus) {
            imgList = getIntent().getStringArrayListExtra("imgUrls");
        }
        uploadEntity = (UploadEntity) getIntent().getSerializableExtra("data");
        if (!uploadStatus) {
            //上传失败进来的
            imgList.clear();
            ArrayList<String> imgListss = uploadEntity.getImage().getImgList();
            KLog.i(imgListss.size() + "=======");
            imgList.addAll(imgListss);
            boolean dataComplete = true;//默认数据是完整的
            for (int i = 0; i < imgList.size(); i++) {
                try {
                    File file = new File(imgList.get(i));
                    if (!file.exists()) {
                        dataComplete = false;
                        imgList.remove(i);
                        if (i < imgList.size()) {
                            i--;
                        }
                    }
                } catch (Exception e) {
                    MyToast.show("文件不存在，请重新选择后上传");
                }
            }
            if (!dataComplete) {
                MyToast.show("有图片被删除，请重新选择图片");
            }
        }
        if (imgList != null) {
            if (imgList.size() < 9) {
                imgList.add("");
            }
        } else {
            imgList.add("");
        }
        NavigationTools.saveUseRecord(this, "2", "25");


        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(gridLayoutManager1);
        GridSpacingItemDecoration gridSpacingItemDecoration = new GridSpacingItemDecoration(3, Utils.dip2px(this, 8), false);
        recyclerView.addItemDecoration(gridSpacingItemDecoration);
        adapter = new MyImagsAdapter(R.layout.item_my_gallery, this, imgList);
        recyclerView.setAdapter(adapter);
        List<String> stringList = new ArrayList<>();
        stringList.add("公开");
        stringList.add("自己可见");
        stringList.add("取消");
        typeDialog = new BottomListsDialog(this, stringList, new SelectDialogListener() {
            @Override
            public void onCancel() {
            }

            @Override
            public void onListItemClick(int position, List<String> list) {
                if (tvType == null) {
                    return;
                }
                if (position == 0) {
                    imgOpenStatus = "0";
                    tvType.setText("公开");
                    typeDialog.setSelect(0);
                } else if (position == 1) {
                    imgOpenStatus = "1";
                    tvType.setText("自己可见");
                    typeDialog.setSelect(1);
                }
                typeDialog.dismiss();
            }
        });

        List<String> originalList = new ArrayList<>();
        originalList.add("原创");
        originalList.add("非原创");
        originalList.add("取消");
        originalDialog = new BottomListsDialog(this, originalList, new SelectDialogListener() {
            @Override
            public void onCancel() {
            }

            @Override
            public void onListItemClick(int position, List<String> list) {
                if (tvOriginal == null) {
                    return;
                }
                if (position == 0) {
                    imgOriginal = "1";
                    tvOriginal.setText("原创");
                    originalDialog.setSelect(0);
                } else if (position == 1) {
                    imgOriginal = "0";
                    tvOriginal.setText("非原创");
                    originalDialog.setSelect(1);
                }
                originalDialog.dismiss();
            }
        });

        if (!uploadStatus) {
            //上传失败进来的
            edKey.setText(uploadEntity.getImage().getImageKeyWord());
            tvChoiceLabel.setText(uploadEntity.getImage().getTagNames());
            provideEmployeeName = uploadEntity.getImage().getProvideEmployeeName();
            provideEmployeeCode = uploadEntity.getImage().getProvideEmployeeCode();
            directoryCode = uploadEntity.getImage().getCatalogCodes();
            directoryName = uploadEntity.getImage().getCatalogNames();
            tvDirectory.setText(directoryName);
            tvProvider.setText(provideEmployeeName);
            imgOpenStatus = uploadEntity.getImage().getImageOpenStatus();
            imgOriginal = uploadEntity.getImage().getOriginal();
            if ("1".equals(imgOpenStatus)) {
                tvType.setText("自己可见");
                typeDialog.setSelect(1);
            } else {
                tvType.setText("公开");
                typeDialog.setSelect(0);
            }
            if ("0".equals(imgOriginal)) {
                tvOriginal.setText("非原创");
                originalDialog.setSelect(1);
            } else {
                tvOriginal.setText("原创");
                originalDialog.setSelect(0);
            }
            shareFlag = Utils.changeNumber(uploadEntity.getImage().getShareFlag());
            if (shareFlag == 1) {
                ivBg.setVisibility(View.VISIBLE);
                ivChoice.setVisibility(View.VISIBLE);
                ivChoice2.setVisibility(View.GONE);
            } else {
                ivBg.setVisibility(View.GONE);
                ivChoice.setVisibility(View.GONE);
                ivChoice2.setVisibility(View.VISIBLE);
            }
        } else {
            //第一次发布逻辑
            provideEmployeeName = new ShareUtils().getString(this, StaticClass.USER_NICKNAME, "");
            provideEmployeeCode = new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, "");
            directoryCode = getIntent().getStringExtra("directoryCode");
            //默认展示自己部门目录
            if (Utils.isNull(directoryCode)) {
                directoryCode = new ShareUtils().getString(this, StaticClass.BELG_CATALOG_CODE, "");
                directoryName = new ShareUtils().getString(this, StaticClass.BELG_ORG_NAME, "");
            } else {
                directoryName = getIntent().getStringExtra("directoryName");
            }
            tvDirectory.setText(directoryName);
            tvProvider.setText(provideEmployeeName);
            typeDialog.setSelect(0);
            originalDialog.setSelect(0);
        }
        if (NetUtils.isGPSEnabled(this)) {
            getPermissions();
        } else {
            showDialog();
        }
    }

    private void showDialog() {
        new XPopup.Builder(this)
                .isDestroyOnDismiss(true)
                .dismissOnTouchOutside(false)
                .asConfirm("提示", "定位服务未开启，请打开定位服务",
                        "取消", "去开启",
                        new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivity(intent);
                                finish();
                            }
                        }, new OnCancelListener() {
                            @Override
                            public void onCancel() {
                                finish();
                            }
                        }, false)
                .show();
    }

    private void startLoc() {
        //声明LocationClient类
        try {
            if (mLocationClient == null) {
                LocationClient.setAgreePrivacy(true);
                mLocationClient = new LocationClient(getApplicationContext());
                LocationClientOption option = new LocationClientOption();
                mLocationClient.registerLocationListener(myListener);
                option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
                option.setCoorType("bd09ll");
                option.setIsNeedAddress(true);
                option.setOpenGps(true);
                option.setScanSpan(1000);
                mLocationClient.setLocOption(option);
            }
            if (mLocationClient != null) {
                mLocationClient.start();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getPermissions() {
        XXPermissions.with(this)
                // 申请单个权限
                .permission(Permission.ACCESS_FINE_LOCATION)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            startLoc();
                        } else {
                            MyToast.show("定位权限未正常授予");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            MyToast.show("被永久拒绝授权，请手动授予定位权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(PublishGalleryActivity.this, permissions);
                        } else {
                            MyToast.show("获取定位权限失败");
                        }
                    }
                });
    }


    private int locationFlag = 0;

    @OnClick({R.id.common_title_back, R.id.tvChoiceLabel, R.id.tvChoieDirectory, R.id.tvChoieLocation, R.id.tvProvider, R.id.tvType, R.id.tvOriginal, R.id.rlChoice, R.id.tv_publish})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.tvChoiceLabel:
                intent = new Intent(this, GallerySingleChoiceLabelActivity.class);
                startActivity(intent);
                break;
            case R.id.tvChoieDirectory:
                intent = new Intent(this, VideoNewCatesActivity.class);
                intent.putExtra("videoType", "4");
                startActivity(intent);
                break;
            case R.id.tvChoieLocation:
                getPermissions();
                break;
            case R.id.tvProvider:
                MyApp.contactEntityLogList.clear();
                intent = new Intent(this, ContactsLogChoiceActivity.class);
                intent.putExtra("source", SOURSE + "");
                startActivity(intent);
                break;
            case R.id.tvType:
                if (typeDialog != null) {
                    typeDialog.show();
                }
                break;
            case R.id.tvOriginal:
                if (originalDialog != null) {
                    originalDialog.show();
                }
                break;
            case R.id.rlChoice:
                if (ivBg == null) {
                    return;
                }
                if (shareFlag == 1) {
                    shareFlag = 0;
                    ivBg.setVisibility(View.GONE);
                    ivChoice.setVisibility(View.GONE);
                    ivChoice2.setVisibility(View.VISIBLE);
                } else {
                    shareFlag = 1;
                    ivBg.setVisibility(View.VISIBLE);
                    ivChoice.setVisibility(View.VISIBLE);
                    ivChoice2.setVisibility(View.GONE);
                }
                break;
            case R.id.tv_publish:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (edKey == null) {
                    return;
                }
                if (imgList.size() <= 1) {
                    MyToast.show("请先添加图片");
                    return;
                }
                Intent intentUpload = new Intent(PublishGalleryActivity.this, UploadFileService.class);
                UploadEntity newUploadEntity = new UploadEntity();
                UploadEntity.ImageBean galleryEntiry = new UploadEntity.ImageBean();
                if (Utils.isNull(imgList.get(imgList.size() - 1))) {
                    imgList.remove(imgList.size() - 1);
                }
                String title = new File(imgList.get(0)).getName();
                galleryEntiry.setImgList(imgList);
                galleryEntiry.setImagePath(imgList.get(0));
                galleryEntiry.setImageTitle(title);
                galleryEntiry.setImageKeyWord(edKey.getText().toString());
                galleryEntiry.setTagCodes(tagCode);
                galleryEntiry.setTagNames(tvChoiceLabel.getText().toString());
                galleryEntiry.setCatalogCodes(directoryCode);
                galleryEntiry.setCatalogNames(directoryName);
                galleryEntiry.setImageUploadLocation(tvLocation.getText().toString());
                galleryEntiry.setImageUploadLocationProvince(province);
                galleryEntiry.setImageUploadLocationCity(city);
                galleryEntiry.setImageUploadLocationCounty(district);
                galleryEntiry.setImageUploadLocationWd(latitude + "");
                galleryEntiry.setImageUploadLocationJd(longitude + "");
                galleryEntiry.setProvideEmployeeCode(provideEmployeeCode);
                galleryEntiry.setProvideEmployeeName(provideEmployeeName);
                galleryEntiry.setImageOpenStatus(imgOpenStatus);
                galleryEntiry.setOriginal(imgOriginal);
                galleryEntiry.setShareFlag(shareFlag + "");
                newUploadEntity.setImage(galleryEntiry);
                if (uploadStatus) {
                    newUploadEntity.setUploadStatus(1);
                    newUploadEntity.setUploadTag(Utils.getCurrentTime2());
                } else {
                    newUploadEntity.setUploadStatus(2);
                    newUploadEntity.setUploadTag(uploadTag);
                }
                newUploadEntity.setProvideEmployeeCode(provideEmployeeCode);
                newUploadEntity.setResourceType("6");
                newUploadEntity.setUploadTitle(title);
                intentUpload.putExtra("data", newUploadEntity);
                intentUpload.putExtra("resourceType", "6");
                startService(intentUpload);
                finish();
                break;
        }
    }

    class MyImagsAdapter extends BaseQuickAdapter<String, BaseViewHolderEx> {
        private Context context;
        private int width, height;

        public MyImagsAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable ArrayList<String> data) {
            super(layoutResId, data);
            this.context = context;
            width = (Utils.getScreenWidthPixel(context) - Utils.dip2px(context, 40)) / 3;
            height = width;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, String item) {
            MyRoundLayout myRl = helper.getView(R.id.myRl);
            ImageView ivBg = helper.getView(R.id.ivBg);
            LinearLayout llDelete = helper.getView(R.id.llDelete);
            LinearLayout llAdd = helper.getView(R.id.llAdd);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) myRl.getLayoutParams();
            params.height = height;
            params.width = width;
            myRl.setLayoutParams(params);
            RelativeLayout.LayoutParams llAddParams = (RelativeLayout.LayoutParams) llAdd.getLayoutParams();
            llAddParams.height = height;
            llAddParams.width = width;
            llAdd.setLayoutParams(llAddParams);
            if (Utils.isNull(item)) {
                llAdd.setVisibility(View.VISIBLE);
                myRl.setVisibility(View.GONE);
            } else {
                llAdd.setVisibility(View.GONE);
                myRl.setVisibility(View.VISIBLE);
                Glide.with(PublishGalleryActivity.this).load(item).into(ivBg);
            }
            llDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    imgList.remove(helper.getItemPosition());
                    if (imgList.size() < 9 && !Utils.isNull(imgList.get(imgList.size() - 1))) {
                        imgList.add("");
                    }
                    adapter.notifyDataSetChanged();
                }
            });
            llAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    requestSTORAGECamer();
                }
            });
            ivBg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new XPopup.Builder(getContext())
                            .hasStatusBarShadow(false)
                            //.dismissOnBackPressed(false)
                            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                            .autoOpenSoftInput(true)
                            .setPopupCallback(new DemoXPopupListener())
                            .asInputConfirm("标题", null, null, "请编辑图片的名称",
                                    new OnInputConfirmListener() {
                                        @Override
                                        public void onConfirm(String text) {
                                            if (!Utils.isNull(text)) {
                                                imgList.set(helper.getItemPosition(), FileUtilss.chageFileName(item, text));
                                                MyToast.show("名称修改成功");
                                            }
                                        }
                                    })
                            .show();
                }
            });

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                //去除+号
                imgList.remove(imgList.size() - 1);
                for (int i = 0; i < selectList.size(); i++) {
                    KLog.i("压缩::" + selectList.get(0).getCompressPath());
                    KLog.i("原图::" + selectList.get(0).getPath());
                    String url = "";
                    if (!Utils.isNull(selectList.get(i).getCompressPath())) {
                        if (selectList.get(i).getCompressPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getCompressPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getCompressPath();
                        }
                    } else {
                        if (selectList.get(i).getPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getPath();
                        }
                    }
                    imgList.add(url);
                }
                KLog.i("======" + imgList.size());
                //根据图片数量判断是否添加+
                if (imgList.size() < 9) {
                    imgList.add("");
                }
                KLog.i("======---" + imgList.size());
                adapter.notifyDataSetChanged();
            }
        }
    }

    private void requestSTORAGECamer() {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {

                            PictureSelector.create(PublishGalleryActivity.this)
                                    .openGallery(SelectMimeType.ofImage())
                                    .isDisplayCamera(true)//是否显示相机入口
                                    .setMaxSelectNum(10 - imgList.size())
                                    .setSelectionMode(SelectModeConfig.MULTIPLE)//多选
                                    .isPreviewImage(true)//是否支持预览图片
                                    .setCompressEngine(ImageFileCompressEngine.createGlideEngine())
                                    .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                                    .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                    .forResult(PictureConfig.CHOOSE_REQUEST);


                        } else {
                            PermissionUtils.errorPermission(PublishGalleryActivity.this, granted, all);
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(PublishGalleryActivity.this, denied, quick);
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
            if (map.containsKey("galleryTagName")) {
                //选择标签
                if (tvChoiceLabel == null) {
                    return;
                }
                tagCode = map.get("galleryTagCode");
                tvChoiceLabel.setText(map.get("galleryTagName"));
            }
            if (map.containsKey("videoCate") && map.containsKey("videoNames")) {
                //选择提目录
                if (tvDirectory == null) {
                    return;
                }
                directoryCode = map.get("videoCate");
                tvDirectory.setText(map.get("videoNames"));
            }
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("CloseContacts")) {
                //选择提供者
                if (MyApp.contactEntityLogList.size() > 0) {
                    ContactEntity contactEntity = MyApp.contactEntityLogList.get(0);
                    MyApp.contactEntityLogList.clear();
                    provideEmployeeCode = contactEntity.getEmployeeCode();
                    provideEmployeeName = contactEntity.getEmployeeName();
                    tvProvider.setText(provideEmployeeName);
                }

            }
        }
    }

    private boolean firstLocation = true;

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location != null) {
                locationFlag++;
                if (tvLocation == null) {
                    return;
                }
                if (!Utils.isNull(location.getAddrStr())) {
                    tvLocation.setText(location.getAddrStr());
                    province = location.getProvince();
                    city = location.getCity();
                    district = location.getDistrict();
                    latitude = location.getLatitude() + "";
                    longitude = location.getLongitude() + "";
                } else {
                    if (firstLocation) {
                        if (mLocationClient != null) {
                            firstLocation = false;
                            mLocationClient.start();
                        }
                    }
                }
                if (locationFlag > 6) {
                    if (null != mLocationClient && mLocationClient.isStarted()) {
                        locationFlag = 0;
                        if (mLocationClient != null) {
                            mLocationClient.stop();
                        }
                    }
                }
            }else {
                if(firstLocation){
                    if (mLocationClient != null) {
                        firstLocation=false;
                        mLocationClient.start();
                    }
                }
            }

        }
    }

    static class DemoXPopupListener extends SimpleCallback {
        @Override
        public void onCreated(BasePopupView pv) {
            Log.e("tag", "onCreated");
        }

        @Override
        public void onShow(BasePopupView popupView) {
            Log.e("tag", "onShow");
        }

        @Override
        public void onDismiss(BasePopupView popupView) {
            Log.e("tag", "onDismiss");
        }

        @Override
        public void beforeDismiss(BasePopupView popupView) {
            Log.e("tag", "beforeDismiss");
        }

        //如果你自己想拦截返回按键事件，则重写这个方法，返回true即可
        @Override
        public boolean onBackPressed(BasePopupView popupView) {
            Log.e("tag", "拦截的返回按键，按返回键XPopup不会关闭了");
            MyToast.show("请先编辑图片名称");
            return true;
        }

        @Override
        public void onKeyBoardStateChanged(BasePopupView popupView, int height) {
            super.onKeyBoardStateChanged(popupView, height);
            Log.e("tag", "onKeyBoardStateChanged height: " + height);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stop();
        }
    }
}
